const {app, BrowserWindow} = require('electron');
const path = require('path');
const registerDBIpc = require('./ipc/dbHandler');
const registerQUESIpc = require('./ipc/quesHandler');
const registerHISTORYIpc = require('./ipc/historyHandler');
const registerSTARIpc = require("./ipc/starHandler");

function createWindow() {
    const win = new BrowserWindow({
        width: 1280,
        height: 720,
        autoHideMenuBar: true,  // 自动隐藏菜单栏
        webPreferences: {
            preload: path.join(__dirname, 'preload.js'),
            contextIsolation: true,
            nodeIntegration: false,
        },
    });
    const isDev = !app.isPackaged;
    if (isDev) {
        win.loadURL('http://localhost:5173');
    } else {
        win.loadFile(path.join(__dirname, 'renderer/dist/index.html'));
    }

    // 确认退出
    if (process.platform !== 'darwin') {
        win.on('close', (e) => {
            const choice = require('electron').dialog.showMessageBoxSync(win, {
                type: 'question',
                buttons: ['否', '是'],
                defaultId: 0,
                cancelId: 0,
                title: '确认退出',
                message: '确定要退出应用吗？'
            });

            if (choice !== 1) {
                // 阻止关闭
                e.preventDefault();
            }
        });
    }
}

function registerIpcHandlers() {
    registerDBIpc(); // 考题库模块
    registerQUESIpc(); // 考题模块（旧）
    registerHISTORYIpc(); // 打印历史记录模块
    registerSTARIpc(); // 收藏试卷模块
}

app.whenReady().then(() => {
    createWindow();

    // 注册各模块的IPC
    registerIpcHandlers();

    // 适配MacOS窗口激活行为
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
})

// 适配MacOS关闭窗口行为
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit();
});
